import 'package:flutter/material.dart';
import 'package:flutter_billi/http/core/hi_error.dart';
import 'package:flutter_billi/http/core/hi_state.dart';
import 'package:flutter_billi/util/color.dart';
import 'package:flutter_billi/util/toast.dart';

/// 通用底层页面 带刷新 分页的框架
/// M  DAO 返回数据模型
/// L  列表数据类型
/// T T为Widget
abstract class HiBaseTabState<M, L, T extends StatefulWidget> extends HiState<T> with AutomaticKeepAliveClientMixin {
  List<L> dataList = [];
  int pageIndex = 1;
  ScrollController scrollController = ScrollController();
  bool loading = false;

  get contentChild;

  @override
  void initState() {
    super.initState();
    scrollController.addListener(() {
      var dis = scrollController.position.maxScrollExtent - scrollController.position.pixels;
      print("dis:$dis");
      if (dis < 300 && loading == false && scrollController.position.maxScrollExtent != 0) {
        // scrollController.position.maxScrollExtent 最大可滚动高度
        // 列表高度 不满 屏幕高度 时 不执行加载更多
        loadData(loadMore: true);
      }
    });
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return RefreshIndicator(
      child: MediaQuery.removePadding(removeTop: true, context: context, child: contentChild),
      color: primay,
      onRefresh: loadData,
    );
  }

  /// 获取对应页码 的数据
  Future<M> getData(int pageIndex);

  /// 从 M 中取出L 数据
  List<L> parseList(M result);

  Future<void> loadData({loadMore = false}) async {
    loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);

    try {
      var result = await getData(currentIndex);
      print('loadata${result}');
      setState(() {
        if (loadMore) {
          dataList = [...dataList, ...parseList(result)];
          if (parseList(result).length != 0) {
            pageIndex++;
          }
        } else {
          dataList = parseList(result);
        }
      });
      Future.delayed(Duration(milliseconds: 1000)).then((value) {
        loading = false;
      });
    } on NeedAuth catch (err) {
      loading = false;
      print(err);
      showWarnToast(err.message);
    } on HiNetError catch (err) {
      loading = false;
      showWarnToast(err.message);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
